package com.ethan.crm.web.interceptor;

import com.ethan.crm.domain.Employee;
import com.ethan.crm.util.PermissionsUtil;
import com.ethan.crm.util.UserContext;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *  登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        //过滤器先将request对象放到对应的线程的ThreadLocal中，这样就可以在对应的线程中取到request对象
        UserContext.set(request);
        //每次请求都会去session中先获取登录用户的信息
        Employee currentUser = (Employee) request.getSession().getAttribute(UserContext.USER_IN_SESSION);
        if (null == currentUser){
            //重定向到登录页
            response.sendRedirect("/login.jsp");
            return false;
        }

        System.out.println("======="+o.getClass());

        if (o instanceof HandlerMethod){
            HandlerMethod method = (HandlerMethod) o;
            String functionPermission = method.getBean().getClass().getName()+":"+method.getMethod().getName();
            //访问的地址该用户是否有权限
            boolean havePermission = PermissionsUtil.checkPermission(functionPermission);
            if (havePermission){//有权限直接放行
                return true;
            }else {
                //判断是页面请求还是ajax请求
                boolean annotationPresent = method.getMethod().isAnnotationPresent(ResponseBody.class);
                if (annotationPresent){
                    //ajax请求
                    response.sendRedirect("/noPermission.json");
                }else {
                    //页面请求
                    response.sendRedirect("/noPermission.jsp");
                }
                return false;
            }
        }

        return true;

    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
